import Taro, { Component } from '@tarojs/taro';
import { View, Picker, Text, Button ,Form,Label,Input} from '@doctorwork/components';
import { connect } from '@tarojs/redux';
import Navigate from '../../components/Navigate/index';
import { rewriteAddMTA } from './../../model/utils/rewrite';
import SelectCar from '../../components/selectCar/index';

import './index.styl';
import { timeFormat } from '../../model/utils/common';

@connect(({ create }) => ({
    ...create
}))
@rewriteAddMTA
export default class Create extends Component {
    config = {
        navigationBarTitleText: '新增加油'
    };
    constructor(props){
        super(props);
        this.state = {
            province: '',
            selector:['北京', '上海', '江苏', '天津', '重庆', '江西', '辽宁', '安徽', '内蒙古', '福建', '宁夏', '甘肃', '青海', '广东', '山东', '广西', '山西', '贵州', '陕西', '海南', '四川', '河北', '西藏', '河南', '新疆', '黑龙江', '吉林', '云南', '湖北', '浙江', '湖南'],
        };
    }

    componentDidMount(){
        const id = this.$router.params.id;
        // 初始化数据
        this.initData(id);
        const province = wx.getStorageSync('province');
        if(province){
            this.setState({
                province
            });
        }
    }
    /**
     * 添加新的车辆
     */
    onAddNewCar(){
        this.initData();
        this.props.dispatch({
            type : 'create/save',
            payload : {
                carModal: false
            }
        });
    }
    /**
     * 获取用户经纬度
     */
    async getUserLocation(){
        const province = wx.getStorageSync('province');
        let location = wx.getStorageSync('location');
        if(location) location = JSON.parse(location);
        this.getOilPrice(province,location);
    }
    getOilPrice(province, location){
        this.props.dispatch({
            type: 'create/getOilPrice',
            payload: {
                province, location
            }
        });
    }

    /**
     * 初始化数据
     * @param {*} province 
     */
    initData(id,province, location={}){
        this.props.dispatch({
            type : 'create/init',
            payload: {id,province,location, callback: ()=>{
                // 只记录第一次经纬度
                if(!id){
                    this.getUserLocation();
                }
            }}
        });
    }
    jumpPrice(){
        this.props.dispatch({
            type  : '$router/forward',
            payload : {
                url : '/pages/price/index'
            }
        });
    }
    // 输入的值改变
    onInputChange(key,e){
        const {detail} = this.props;
        detail[key] = e.detail.value;
        let { price,oil_amount,total_price ,mileage} = detail;
        if(price && key == 'price'){
            if(oil_amount){
                total_price = (price * oil_amount).toFixed(2);
            }else if(total_price)(
                oil_amount = (total_price / price).toFixed(2)
            );
        }else if(oil_amount && key == 'oil_amount'){
            if(price){
                total_price = (price * oil_amount).toFixed(2);
            }else if(total_price){
                price = (total_price / oil_amount).toFixed(2);
            }
        }else if(total_price && key == 'total_price'){
            if(price){
                oil_amount = (total_price / price).toFixed(2);
            }else if(oil_amount){
                price = (total_price / oil_amount).toFixed(2);
            }
        }
        console.log(detail);
        this.props.dispatch({
            type : 'create/save',
            payload : {
                detail : {
                    ...detail,
                    price,oil_amount,total_price,mileage
                },
            }
        });
    }
    validate(){
        const {price=0, mileage=0, total_price=0, oil_amount=0 , carNumber} = this.props.detail;
        if(!carNumber){
            return '请先添加车辆';
        }else if(price>20 || price<=0){
            return '单价输入有误';
        }else if(total_price <= 0){
            return '金额输入有误';
        }else if(oil_amount <= 0){
            return '油量输入有误';
        }else if(mileage <= 0){
            return '里程输入有误';
        }
        return null;
    }

    addOil(){
        const valid = this.validate();
        if(valid){
            wx.showToast({
                icon: 'error',
                duration: 3000,
                title: valid
            });
        }else{
            this.props.dispatch({
                type : 'create/addOil'
            });
        }
        
    }

    addCar(){
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : '/pages/car/index',
            }
        });
    }
    /**
     * 切换日期
     * @param {*} e 
     */
    onDateChange(e){
        const oilDate = e.target.value;
        const {detail} = this.props;
        this.props.dispatch({
            type : 'create/save',
            payload : {
                detail : {
                    ...detail,
                    oilDate
                },
            }
        });
    }
    /**
     * 切换时间
     * @param {*} e 
     */
    onTimeChange(e){
        const oilSecond = e.target.value;
        const {detail} = this.props;
        this.props.dispatch({
            type : 'create/save',
            payload : {
                detail : {
                    ...detail,
                    oilSecond
                },
            }
        });
    }
    // 
    changeCarModal(carModal){
        this.props.dispatch({
            type : 'create/save',
            payload : {
                carModal
            }
        });
    }
    /**
     * 选中车辆
     * @param {*} carNumber 
     */
    onCarSelected(carNumber){
        this.props.dispatch({
            type: 'create/carNumberChange',
            payload: {
                carNumber
            }
        });
    }
    /**
     * 取消选择车辆
     */
    onCarCancel(){
        this.props.dispatch({
            type : 'create/save',
            payload : {
                carModal: false
            }
        });
    }
    /**
     * 
     * @param {*} e 
     */
    provinceChange(e){
        console.log('选择省份:',e);
        const index = e.detail.value;
        const {selector,date} = this.state;
        const province =  selector[index];
        this.setState({province});
        wx.setStorageSync('province',province);
        this.getUserLocation();
    }
    render() {
        const {detail,carModal,carList} = this.props ;
        const {selector, province} = this.state;
        const disabled = !(detail.price&&detail.oil_amount&&detail.total_price&detail.mileage);
        console.log(detail.oilTime);
        const endTime = timeFormat(Date.now()+86399,'YYYY-MM-DD');
        return (
            <View className='container'>
                <Navigate
                    title='新增加油'
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                />
                <View className='oil-container'>
                    {
                        carModal && <SelectCar 
                            carList={carList} 
                            carNumber={detail.carNumber} 
                            onCarSelected={this.onCarSelected.bind(this)} 
                            onAddNewCar={this.onAddNewCar.bind(this)}
                            onClose={this.onCarCancel.bind(this)}
                        />
                    }
                    <View className='input-item'>
                        <Label className='item-title'>车辆: </Label>
                        {
                            detail.carNumber ? <Text className='add-car' onClick={this.changeCarModal.bind(this,true)} data-name={detail.carNumber}>{detail.carNumber}</Text> :
                                <Text className='add-car' onClick={this.changeCarModal.bind(this)} data-name='点击添加车辆'>添加车辆</Text>
                        }
                        
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>加油日期: </Label>
                        <Label>
                            <View className='picker'>
                                <Picker mode='date' onChange={this.onDateChange} value={detail.oilDate} end={endTime}>
                                    {detail.oilDate} >
                                </Picker>
                            </View>
                        </Label>
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>加油时间: </Label>
                        <Label>
                            <View className='picker'>
                                <Picker mode='time' onChange={this.onTimeChange} value={detail.oilSecond} end={endTime}>
                                    {detail.oilSecond} >
                                </Picker>
                            </View>
                        </Label>
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>省份: </Label>
                        <Picker mode='selector' value={province}  range={selector} onChange={this.provinceChange}>
                            {province || '请选择省份'} >
                        </Picker>
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>单价: </Label>
                        <Input
                            type='digit'
                            placeholder='请输入单价'
                            maxlength='11'
                            value={detail.price}
                            className='text-right'
                            onInput={this.onInputChange.bind(this,'price')}
                        />
                        <View className='price-info'>{detail.province}·#{detail.oilType}当前油价: {detail.orgprice}</View>
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>金额(¥): </Label>
                        <Input
                            type='digit'
                            placeholder='请输入加油金额'
                            maxlength='11'
                            value={detail.total_price}
                            className='text-right'
                            onInput={this.onInputChange.bind(this, 'total_price')}
                        />
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>油量(L): </Label>
                        <Input
                            type='digit'
                            placeholder='请输入油量'
                            maxlength='11'
                            value={detail.oil_amount}
                            className='text-right'
                            onInput={this.onInputChange.bind(this,'oil_amount')}
                        />
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'>总里程数(KM): </Label>
                        <Input
                            type='digit'
                            placeholder='请输入当前行驶里程'
                            maxlength='11'
                            value={detail.mileage}
                            className='text-right'
                            onInput={this.onInputChange.bind(this, 'mileage')}
                        />
                    </View>
                    
                </View>
                <View className='footer-fit'></View>
                <View className='footer'>
                    <Button onClick={this.addOil.bind(this)} className={disabled ? 'oil-btn disabled' : 'oil-btn'} data-name='确定'>
                        确 定
                    </Button>
                </View>
            </View>

        );
    }
}
